package com.zhigongtech.tender.sys.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhigongtech.extension.entry.DataPermit;
import com.zhigongtech.tender.sys.entity.Office;
import com.zhigongtech.tender.sys.entity.User;
import com.zhigongtech.tender.sys.service.IOfficeService;
import com.zhigongtech.tender.sys.service.IPermissionDataService;
import com.zhigongtech.tender.sys.service.IUserService;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @ClassName:  PermissionDataServiceImpl   
 * @Description: 数据权限实现类
 * @author: Alan
 * @date:   2019-06-17 15:05:18
 *     
 */
@Service
@Transactional
@Slf4j
public class PermissionDataServiceImpl implements IPermissionDataService {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IOfficeService officeService;
	
	/**
	 * params：1-数据表对应的创建者字段(默认：create_by)
	 */
	private static final String dsql="select 1 from SYS_USER u join SYS_OFFICE o on u.office_id = o.id where u.id = %s "
			+ "and ((o.id= '%s' or o.PARENT_IDS %s '%s') or u.id = '%s')";

	@Override
	public <T> QueryWrapper<T> addPermission(QueryWrapper<T> query, String account, String dbColumeEqUserId) {
		User user = userService.getUserByAccount(account);
		if(DataPermit.Scope.ALL.equals(user.getScope())) {
			return query;
		}
		Office office = officeService.getById(user.getOfficeId());
		if(office == null) {
			return query;
		}
		String existsSql=null;
		if(DataPermit.Scope.COMPANY.equals(user.getScope())) {
			existsSql = getSql(dbColumeEqUserId, office.getId(), office.getParentIds(), user.getId(), DataPermit.Symbol.EQ);
		}else if(DataPermit.Scope.COMPANY_AND_CHILD.equals(user.getScope())){
			existsSql = getSql(dbColumeEqUserId, office.getId(), office.getParentIds(), user.getId(), DataPermit.Symbol.LIKE);
		}
		if(StringUtils.isNotBlank(existsSql)) {
			query.exists(existsSql);
		}
		return query;
	}
	
	/**
	 * 
	 * @Title: getSql   
	 * @Description: exists sql 语句 
	 * by Alan 2019-06-17 16:50:52
	 * @param dbColumeEqUserId  数据表存储创建者的字段，传入参数格式：表名.字段名  <<TableName>>.<<ColumnName>>
	 * @param officeId 用户归属公司ID
	 * @param parentIds 公司上级机构
	 * @param userId  用户ID
	 * @param sqlSymbol  数据连接符
	 * @return      
	 * @return  String
	 */
	private String getSql(String dbColumeEqUserId, String officeId, String parentIds, String userId, String sqlSymbol) {
		String ids = parentIds+officeId+",";
		if(DataPermit.Symbol.LIKE.equals(sqlSymbol)) {
			ids +="%";
		}
		return String.format(dsql, dbColumeEqUserId, officeId, sqlSymbol, ids, userId);
	}

	
//	public static void main(String[] args) {
//		String tmp = String.format(dsql, "u.create_by", "111", "like", "eiei%", "tt");
//		System.out.println(tmp);
//		String tm = DataPermit.Scope.COMPANY;
//	}
}
